<template>
  <div class="app-container">
    <el-form v-if="!isCompany" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">
      <el-form-item label="单位名称" prop="compName">
        <el-input v-model="queryParams.compName" placeholder="请输入单位名称" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row v-if="!isCompany" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:company:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:company:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['system:company:export']">批量导入</el-button>
      </el-col>
      <div v-if="totalCount">{{ totalCount }}</div>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单位ID" align="center" prop="id" />
      <el-table-column label="单位名称" align="center" prop="compName" />
      <!-- <el-table-column label="账号" align="center" prop="" /> -->
      <el-table-column label="单位类型" align="center" prop="compType" />
      <el-table-column label="所属行业" align="center" prop="compIndustry" />
      <el-table-column label="审核状态" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <span v-if="scope.row.isExamine === 0" style="color: #E6A23C;">待审核</span>
          <span v-if="scope.row.isExamine === 1" style="color: #67C23A;">通过</span>
          <span v-if="scope.row.isExamine === 2" style="color: #F56C6C">未通过</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="岗位发布" align="center" prop="" />
      <el-table-column label="账号状态" align="center" prop="" /> -->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['system:company:edit']">修改密码</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['system:company:edit']"
            @click="handleUpdate(scope.row, 'edit')">修改</el-button>
          <el-button size="mini" type="text" v-hasPermi="['system:company:remove']"
            @click="handleUpdate(scope.row, 'isExamine')">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['system:company:edit']"
            @click="handlePasswordDialog(scope.row)">修改密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 经纬度 -->
    <el-dialog title="获取经纬度" :visible.sync="openDialog" append-to-body width="80%">
      <iframe :src="'https://lbs.qq.com/getPoint/'" width="100%" height="750px" frameBorder="0"></iframe>
    </el-dialog>

    <!-- 添加或修改人才招聘单位信息对话框 -->
    <el-dialog class="company-form" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="单位名称" prop="compName">
          <el-input v-model="form.compName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="单位Logo">
          <image-upload :limit="1" resolution="176*132像素" v-model="form.compLogo" />
        </el-form-item>

        <el-form-item label="所属行业" prop="compIndustry">
          <el-input v-model="form.compIndustry" placeholder="请输入所属行业" />
        </el-form-item>
        <el-form-item label="单位类型" prop="compType">
          <el-select v-model="form.compType" placeholder="请选择单位类型">
            <el-option v-for="(item, index) in companyTypeList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业规模" prop="compScale">
          <!-- <el-input v-model="form.compScale" placeholder="请输入企业规模" /> -->
          <el-select v-model="form.compScale" placeholder="请选择企业规模">
            <el-option v-for="(item, index) in compScaleList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="liaison">
          <el-input v-model="form.liaison" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.liaisonPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="单位网站地址">
          <el-input v-model="form.compWebsite" placeholder="请输入单位官方网站地址" />
        </el-form-item>
        <el-form-item label="单位区域" prop="compArea">
          <el-select v-model="form.compArea" placeholder="请选择单位区域">
            <el-option v-for="(item, index) in compAddrList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位地址" prop="compAddr">
          <el-input v-model="form.compAddr" placeholder="请输入单位地址" />
        </el-form-item>
        <el-form-item label="经纬度" class="is-required" prop="longitudeAndLatitude">
          <el-input v-model.trim="form.longitudeAndLatitude" placeholder="请输入经纬度" />
          <el-button class="mt10" type="primary" @click="openDialog = true">选择经纬度</el-button>
        </el-form-item>
        <el-form-item prop="userName" label="账号" v-if="operateType === 'add'">
          <el-input v-model="form.userName" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" v-if="operateType === 'add'">
          <el-input v-model="form.password" type="password" auto-complete="off" placeholder="密码">
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码" v-if="operateType === 'add'">
          <el-input v-model="form.confirmPassword" type="password" auto-complete="off" placeholder="确认密码">
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item label="单位简介" prop="compBlurb">
          <editor v-model="form.compBlurb" placeholder="请输入单位简介" :min-height="200" />
        </el-form-item>
        <!-- <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="维度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入维度" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="operateType === 'isExamine'">
        <el-button type="primary" @click="handleExamine(1)">审核通过</el-button>
        <el-button @click="handleExamine(2)">审核不通过</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button type="primary" @click="submitForm">{{ operateType === 'add' ? '新增企业' : '修改企业信息' }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码 -->
    <el-dialog v-if="passwordOpen" class="company-form" title="修改密码" :visible.sync="passwordOpen" append-to-body>
      <el-form ref="passwordForm" :model="registerForm" :rules="rules" label-width="100px">
        <el-form-item label="账号">
          <el-input v-model="registerForm.userName" disabled type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="registerForm.password" type="password" auto-complete="off" placeholder="密码"
            @keyup.enter.native="handleRegister">
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input v-model="registerForm.confirmPassword" type="password" auto-complete="off" placeholder="确认密码"
            @keyup.enter.native="handleRegister">
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEditPasswrod">确认</el-button>
        <el-button @click="passwordOpen = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 公司导入对话框 -->
    <el-dialog title="批量导入招聘公司" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { validatePhone, validateLandLine } from '@/utils/validate'
import { getHireDicts } from '@/api/system/dict/data'
import { listCompany, getCompany, delCompany, addCompany, updateCompany, getComAccount, updateAccountData, companyCount, importCompany } from "@/api/system/company";

export default {
  name: "Company",
  data() {
    const equalToPassword = (rule, value, callback) => {
      const formType = this.passwordOpen ? this.registerForm.password : this.form.password
      console.log(formType, 'formType')
      if (formType !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    const validatePhoneNum = (rule, value, callback) => {
      if (!validatePhone(value) && !validateLandLine(value)) {
        callback(new Error('联系方式格式不正确'))
      }
      callback()
    }
    return {
      // 遮罩层
      loading: true,
      openDialog: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      passwordOpen: false,
      totalCount: '',
      // 总条数
      total: 0,
      // 人才招聘单位信息表格数据
      companyList: [],
      companyTypeList: [],
      compScaleList: [],
      compAddrList: [],
      // 弹出层标题
      title: "",
      operateType: "",
      registerForm: {
        userName: '',
        password: '',
        confirmPassword: ''
      },
      // 是否显示弹出层
      open: false,
      isEdit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        compName: null,
        compLogo: null,
        compWebsite: null,
        compBlurb: null,
        compType: null,
        compIndustry: null,
        compScale: null,
        compStatus: null,
        isExamine: null,
        liaison: null,
        liaisonPhone: null,
        compAddr: null,
        compArea: null,
        longitude: null,
        latitude: null,
        longitudeAndLatitude: null,
      },
      // 表单参数
      form: {},
      // 公司导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/company/import"
      },
      // 表单校验
      rules: {
        compName: [
          { required: true, message: "单位名称不能为空", trigger: "blur" }
        ],
        // compLogo: [
        //   { required: true, message: "单位LOGO不能为空", trigger: "blur" }
        // ],
        compType: [
          { required: true, message: "单位类型不能为空", trigger: "blur" }
        ],
        compIndustry: [
          { required: true, message: "单位所属行业不能为空", trigger: "blur" }
        ],
        compScale: [
          { required: true, message: "单位规模不能为空", trigger: "blur" }
        ],
        // liaisonPhone: [
        //   { required: true, message: "单位联系电话不能为空", trigger: "blur" },
        //   { validator: validatePhoneNum, trigger: ['blur', 'change'] }
        // ],
        compAddr: [
          { required: true, message: "单位地址不能为空", trigger: "blur" }
        ],
        compArea: [
          { required: true, message: "单位区域不能为空", trigger: "blur" }
        ],
        longitudeAndLatitude: [
          { required: true, message: "单位经纬度不能为空", trigger: "blur" }
        ],
        compBlurb: [
          { required: true, message: "单位简介不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],

        //compType
      },
      // passwordRules: {
      //   userName: [
      //     { required: true, trigger: "blur", message: "请输入您的账号" },
      //     { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
      //   ],
      //   password: [
      //     { required: true, trigger: "blur", message: "请输入您的密码" },
      //     { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" },
      //     { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
      //   ],
      //   confirmPassword: [
      //     { required: true, trigger: "blur", message: "请再次输入您的密码" },
      //     { required: true, validator: equalToPassword2, trigger: "blur" }
      //   ],
      // }
    };
  },
  created() {
    console.log(this.isCompany, 'created')
    this.getList();
    this.getHireDicts();
    this.getCompanyCount();
  },
  computed: {
    isCompany() {
      return this.$store.state.user.roles[0] === 'company' && !!this.$store.state.user.userData.compId
    },
    companyId() {
      return this.$store.state.user.userData.compId
    }
  },
  methods: {
    /** 查询人才招聘单位信息列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then(response => {
        this.companyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取字典
    getHireDicts() {
      getHireDicts().then(res => {
        this.companyTypeList = res.data.filter(item => item.field === 'compType')[0].dicts
        this.compScaleList = res.data.filter(item => item.field === 'compScale')[0].dicts
        this.compAddrList = res.data.filter(item => item.field === 'stationAddr')[0].dicts
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        compName: null,
        compLogo: null,
        compWebsite: null,
        compBlurb: null,
        compType: null,
        compIndustry: null,
        compScale: null,
        compStatus: null,
        userName: null,
        password: null,
        confirmPassword: null,
        isExamine: null,
        liaison: null,
        liaisonPhone: null,
        compAddr: null,
        longitude: null,
        latitude: null,
        longitudeAndLatitude: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getCompanyCount()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.operateType = 'add'
      this.open = true;
      this.title = "添加人才招聘单位信息";
    },
    /** 修改按钮操作 审核按钮操作 */
    handleUpdate(row, type) {
      this.reset();
      this.operateType = type
      const id = row.id || this.ids
      getCompany(id).then(response => {
        this.form = response.data;
        const tempStr = response.data.latitude + ',' + response.data.longitude
        this.$set(this.form, 'longitudeAndLatitude', tempStr)
        this.open = true;
        if (type === 'edit') {
          this.title = "修改人才招聘单位信息";

        } else {
          this.title = "单位信息审核";
        }
      });
    },
    handlePasswordDialog(row) {
      this.passwordOpen = true
      getComAccount(row.id).then(res => {
        this.registerForm = res.data
      })
    },
    // 修改密码
    handleEditPasswrod() {
      this.$refs["passwordForm"].validate(valid => {
        if (valid) {
          updateAccountData(this.registerForm).then(res => {
            this.$modal.msgSuccess("修改成功");
            this.passwordOpen = false;
            this.getList();
          })
        }
      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.latitude = this.form.longitudeAndLatitude.split(',')[0]
          this.form.longitude = this.form.longitudeAndLatitude.split(',')[1]

          if (this.form.id != null) {
            updateCompany(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getCompanyCount()
            });
          } else {
            addCompany(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getCompanyCount()
            });
          }
        }
      });
    },

    // 审核
    handleExamine(status) {
      this.form.isExamine = status
      updateCompany(this.form).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.open = false;
        this.getList();
        this.getCompanyCount()
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除人才招聘单位信息编号为"' + ids + '"的数据项？').then(function () {
        return delCompany(ids);
      }).then(() => {
        this.getList();
        this.getCompanyCount()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 导入
    handleImport() {
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      const fileUrl = require('@/assets/xlsxTemplate/companyTemplate.xlsx')
      const link = document.createElement('a')
      link.href = fileUrl
      link.download = '招聘公司管理-数据导入模板.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.code === 200) {
        this.$modal.msgSuccess("导入成功");
        this.getList();
        this.getCompanyCount()
      } else {
        this.$modal.msgError("导入失败");
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      }
    },
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/company/export', {
        ...this.queryParams
      }, `company_${new Date().getTime()}.xlsx`)
    },
    //  统计数据
    getCompanyCount() {
      companyCount().then(res => {
        this.totalCount = res.data
      })
    }
  }
};
</script>
<style lang="scss">
.company-form .el-dialog__body {
  max-height: 700px;
  overflow-y: auto;
}
</style>